﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO; 
using System.Collections;




namespace PrjSerails
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();              //初始化元件  
        }
        
        string InputData = String.Empty;
        string tex= String.Empty;               //建空字符串
        int shu=0,temp1=0;
        byte[] read1;
        delegate void SetTextCallback(string text);
        
     
       
        
         public string GetTime()
        {
            string TimeInString="";
            int hour=DateTime.Now.Hour;
            int min=DateTime.Now.Minute;
            int sec=DateTime.Now.Second;

            TimeInString=(hour < 10)?"0" + hour.ToString() :hour.ToString();
            TimeInString+=":" + ((min<10)?"0" + min.ToString() :min.ToString());
            TimeInString+=":" + ((sec<10)?"0" + sec.ToString() :sec.ToString());
            return TimeInString;
        }

        private void Clock_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            
             textBox1.Text=GetTime();      
            
        }
       
        
        
        
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();

            // Add all port names to the combo box:
            foreach (string port in ports)
            {
                cmbComSelect.Items.Add(port);
            }
        }

        private void cmbComSelect_SelectedIndexChanged(object sender, EventArgs e)
        {            
            port.PortName = cmbComSelect.SelectedItem.ToString();
            stsStatus.Text = port.PortName + "比特率为9600，数据位为8位，停止位为1位";

            if (port.IsOpen) port.Close();            

            // try to open the selected port:

            try
            {
                port.Open();
            }
            // give a message, if the port is not available:
            catch
            {
                MessageBox.Show("Serial port " + port.PortName + " cannot be opened!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbComSelect.SelectedText = "";
                stsStatus.Text = "选择COM口!";
            }
        }

private void btnSend_Click(object sender, EventArgs e)   //发数据16进制数或其他
        {    
        	if(checkBox1.Checked == true)
        	{	
             byte[]  charValue=new byte[100];
            int i=0;
           string[] hexValuesSplit = this.txtOut.Text.Split(' ',',');
           foreach (String hex in hexValuesSplit)
{  
	int value = Convert.ToInt32(hex, 16);
	charValue[i] =(byte)value;
	i++;
 }
port.Write(charValue,0,i);
        	}
      else 
       {
       	byte[] writeBuffer =Encoding.UTF8.GetBytes(this.txtOut.Text);
            if (port.IsOpen) 
            	port.Write(writeBuffer,0,writeBuffer.Length);//Line(txtOut.Text);
            else MessageBox.Show("Serial port is closed!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Error);
           
        
       }
        
        }
              
        private void btnClear_Click(object sender, EventArgs e) //清除文本数据
        {
            txtIn.Clear();
            textBox1.Clear();
            
        }

        private void SetText(string text )   //接收显示数据
        {
            int j;
            if (this.txtIn.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else 
            	
            {
            	
             if(checkBox2.Checked == true)
            { 	
                
            	this.txtIn.Text+=text; 
            	
            	for(j=0;j<temp1;j++)
            	{
            		if(read1[j]==0)
            		{ temp1=0;j=0;break;}
            	
            		
            		
            		this.textBox1.Text+=string.Format("{0:x}",(int)read1[j])+" ";
            	}
            	
            	}
          
            else
            	
            {   
            	this.textBox1.Text += text;
			    
            	
            	this.txtIn.Text+=text;
            	
            	tex+=text;
            }
		    }
        }
      
       
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           
            byte[] readBuffer = new byte[port.ReadBufferSize];
            port.Read(readBuffer, 0,readBuffer.Length);
           	read1=readBuffer;
            temp1=readBuffer.Length;
           
           	 SetText(Encoding.UTF8.GetString(readBuffer));
         }

 
        
        void 读取温度Click(object sender, EventArgs e)  //按钮发送0xfd
        {
        	byte[] writeBuffer =new byte[1];
             writeBuffer[0]=0xfd;
             if (port.IsOpen)
           	port.Write(writeBuffer,0,1);
            else MessageBox.Show("Serial port is closed!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Error);
          
        	
       
        }
        
        void Button1Click(object sender, EventArgs e)//文件保存
        {
        	
        	while(System.IO.File.Exists(@"myfile"+shu+".txt")) 
                   shu++;
        	
        	// 在当前目录创建一个文件myfile.txt，对该文件具有读写权限
        	
        		FileStream fsMyfile = new FileStream("myfile"+shu+".txt" , FileMode.Create, FileAccess.ReadWrite);
        	
        	
		// 创建一个数据流写入器，和打开的文件关联
		StreamWriter swMyfile = new StreamWriter(fsMyfile);
		
        // 以文本方式写一个文件
		swMyfile.WriteLine(GetTime()); 
        swMyfile.WriteLine(this.txtIn.Text);
		
        // 冲刷数据(把数据真正写到文件中去)
        // 注释该句试试看，程序将报错
        swMyfile.Flush();
        }
      
        
       
        
        void TxtInTextChanged(object sender, EventArgs e)
        {
        	
        }
        
        void StatusStrip1ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
        	
        }
        
        void StsStatusClick(object sender, EventArgs e)
        {
        	
        }
        
        void GroupBox2Enter(object sender, EventArgs e)
        {
        	
        }
        
        void Label1Click(object sender, EventArgs e)
        {
        	this.label1.Text =GetTime();
        }
        
        void Timer1Tick(object sender, EventArgs e)
        {
        	this.label1.Text =GetTime();
        }
        
        
        
        void CheckBox2CheckedChanged(object sender, EventArgs e)
        {
        	
        }
    
    
     void CheckBox1CheckedChanged(object sender, System.EventArgs e)
        {
        	
        }
        SaveFileDialog sfd = new SaveFileDialog();
        void Button2Click(object sender, System.EventArgs e)
        {
        	if(sfd.ShowDialog() == DialogResult.OK)

        {

            string fileName = sfd.FileName;

            SaveFile(fileName);

        }
         
      }
    
     protected void SaveFile(string fileName)

    {

        try

        {

            Stream stream = File.OpenWrite(fileName);

            using(StreamWriter writer = new StreamWriter(stream))

            {
            	writer.Write(GetTime()); 
                writer.Write("\r\n"); 
            	writer.Write(textBox1.Text);

            }

        }

        catch(IOException ex)

        {

            MessageBox.Show(ex.Message,"Simple Editor",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);

        }

    }

     private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
     {

     }

     private void label6_Click(object sender, EventArgs e)
     {

     }

     private void label9_Click(object sender, EventArgs e)
     {

     }
    
    }
    }

